<template>
  <div class="app-container">
    <!-- 搜索区 -->
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable size="small" style="width: 240px" />
      </el-form-item>
      <el-form-item label="检验日期" prop="checkDate">
        <el-date-picker v-model="queryParams.checkDate" type="date" placeholder="选择日期"
          value-format="yyyy-MM-dd  HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="质检单号" prop="qualityNumber">
        <el-input v-model="queryParams.qualityNumber" placeholder="请输入质检单号" clearable size="small"
          style="width: 240px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small" style="width: 200px">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="结论" prop="acceptanceNumber">
        <el-select v-model="queryParams.acceptanceNumber" placeholder="请选择结论" clearable size="small"
          style="width: 200px">
          <el-option v-for="dict in conclusionOptions" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['set:model:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cpList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="质检单号" prop="qualityNumber" width="120" align="center" />
      <el-table-column label="产品名称" prop="productName" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="检验日期" prop="checkDate" :show-overflow-tooltip="true" width="150" align="center" />
      <el-table-column label="产品型号" prop="productModel" :show-overflow-tooltip="true" width="150" align="center" />
      <!-- <el-table-column label="判定OK/NG" prop="determine" :show-overflow-tooltip="true" width="100" align="center" /> -->
      <el-table-column label="检验数量" prop="checkoutNumber" :show-overflow-tooltip="true" width="100" align="center" />
      <el-table-column label="检验依据" prop="inspectionStandard" :show-overflow-tooltip="true" width="100"
        align="center" />

      <el-table-column label="结论" prop="acceptanceNumber" :show-overflow-tooltip="true" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.acceptanceNumber === '1'? "合格": "不合格" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检验类别" prop="belowStandard" :show-overflow-tooltip="true" width="100" align="center" >
        <template slot-scope="scope">
          <span>{{ scope.row.belowStandard === '0'? "成品检验单": scope.row.belowStandard == '1' ? "过程检验单" : "来料检验单"}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" :show-overflow-tooltip="true" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.status === '0'? "待检验": scope.row.status == '1' ? "检验中" : "已完成"}}</span>
        </template>
      </el-table-column>
      </el-table-column>
      <el-table-column label="操作" align="center" width="480" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" icon="el-icon-upload2" :disabled="scope.row.status==='2'"
            @click="handleImport(scope.row)">上传</el-button>
          <el-button size="mini" type="success" icon="el-icon-link"
            @click="detail(scope.row)">附件详情</el-button> 
            <el-button size="mini" type="primary" @click="handleRkd(scope.row)" :disabled="scope.row.judge==='1'"
            v-if="scope.row.status==='2'">生成成品入库单</el-button>
          <el-button size="mini" type="danger" icon="el-icon-delete" v-if="scope.row.status==='0'"
            :disabled="scope.row.status==='2'" @click="handleDelete(scope.row)">删除</el-button>
             
          <el-button size="mini" type="primary" :disabled="scope.row.status==='2'"
            @click="completed(scope.row)">完成</el-button>
          <el-link type="primary" style="margin: 0 0 0 10px;" @click="goPage(scope.row)">问题反馈</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="质检单号" prop="qualityNumber">
              <el-input v-model="form.qualityNumber" placeholder="请输入质检单号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验日期" prop="checkDate">
              <el-date-picker v-model="form.checkDate" type="date" placeholder="请选择检验日期"
                value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>

            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品型号" prop="productModel">
              <el-input v-model="form.productModel" placeholder="请输入产品型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验数量" prop="checkoutNumber">
              <el-input-number v-model="form.checkoutNumber" placeholder="请输入检验数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验依据" prop="inspectionStandard">
              <el-input v-model="form.inspectionStandard" placeholder="请输入检验依据" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结论" prop="acceptanceNumber">
              <el-select v-model="queryParams.acceptanceNumber" placeholder="请选择结论" clearable size="small"
                style="width: 200px">
                <el-option v-for="dict in conclusionOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检验类别" prop="belowStandard">

              <el-select v-model="form.belowStandard" placeholder="请选择检验类别" clearable size="small">
                <el-option v-for="dict in belowStandardOptions" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" clearable size="small">
                <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                  :value="dict.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-col :span="12">
          <el-form-item label="判定OK/NG" prop="determine">
            <el-select v-model="form.determine" placeholder="请选择状态判定OK/NG" clearable size="small">
              <el-option v-for="dict in statusPdOptions" :key="dict.dictValue" :label="dict.dictLabel"
                :value="dict.dictValue" />
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 上传-->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload v-show="upload.uploadShow" ref="upload" :limit="5" accept=".png,.jpg,.xls,.xlsx,.doc"
        :headers="upload.headers" :action="upload.url" :disabled="upload.isUploading" :http-request="httpRequest"
        multiple :on-progress="handleFileUploadProgress" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“jpg”“png”“.doc”“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <!-- 附件 -->

      <el-upload v-show="upload.downloadShow" :on-preview="handlePreview" multiple :limit="5" :on-exceed="handleExceed"
        :on-remove="delFile" :file-list="upload.fileList" show-file-list :action="upload.url">
        <div v-for="item in upload.fileList">
          <p>{{item.filename}}</p>
        </div>
      </el-upload>
      <div v-show="upload.downloadShow" v-if="upload.fileList.length===0" style="margin-left: 100px;">暂无文件，请先上传</div>
      <div v-show="upload.uploadShow" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" v-loading="upload.submitLoading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="upload.previewOpen" width="400px" height="500px" title="图片预览">
      <img alt="logo" style="width: 100%;height: 100%;" :src="upload.previewImage" />
    </el-dialog>
  </div>
</template>

<script>
  import {
    listSetModel,
    getSetModel,
    delSetModel,
    addSetModel,
    updateSetModel,
    exportSetModel,
    importTemplate,
    dataScope,
  } from "@/api/parameter/set_model";
  import config from "../../../../vue.config";
  import { getcpList, addCP, delCp, downloadCp, delFile, getFile, preImages, downloadFile, completedCp } from "@/api/mass/end";
  import { uploadCp } from "@/api/upload";
  import { getToken } from "@/utils/auth";
  import Axios from "axios";
  export default {
    name: "End",
    data() {
      return {
        //检验日期
        valueDate: '',
        // 状态字典
        statusOptions: [],
        //结论字典
        conclusionOptions: [],
        belowStandardOptions: [],
        statusPdOptions: [],
        //检验记录
        inspectionRecordOptions: [],
        // 上传
        upload: {
          submitLoading: false,
          fileList: [],
          uploadShow: false,
          downloadShow: false,
          previewOpen: false,
          previewImage: '',
          uploadRes: {},
          uploadFiles: [],
          fileNameList: [],
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/system/file/uploads",
        },
        rowId: '',
        // 遮罩层
        loading: true,
        // 选中数组
        qualityNumbers: [],
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 角色表格数据
        cpList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          product: undefined,
          qualityNumber: undefined,
          checkDate: '',
          product: '',
        },
        // 表单参数
        form: {
          belowStandard: '0'
        },
        defaultProps: {
          children: "children",
          label: "label",
        },
        // 表单校验
        rules: {
          qualityNumber: [
            { required: true, message: "质检单号不能为空", trigger: "blur" },
          ],
          productName: [
            { required: true, message: "产品名称不能为空", trigger: "blur" },
          ],


        },
      };
    },
    created() {
      this.getList();
      this.getDicts("cp_jyd_status").then((response) => {
        this.statusOptions = response.data;
      });
      this.getDicts("conclusion").then((response) => {
        this.conclusionOptions = response.data;
      });
 
      this.belowStandardOptions = [{ value: 0, label: '成品检验单' }]
    },
    methods: {
         //生成入库单
         handleRkd(row) {
              
              this.$confirm(
                  '请确认产品名称为"' + row.productName + '"立即生成入库单？',
                  "警告",
                  {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                      type: "warning",
                  }
              ).then(() => {
                  rkdLld(row).then(res => {
                      this.msgSuccess("已生成入库单");
                      // this.$router.push({ pathname: '/cangku/rukuGen/ruku', query: {} })
                      this.$router.push('/cangku/rukuGen/cprk')
                  })
              })


          },
      //完成
      completed(row) {
        const params={id:row.id,status:row.status}
        this.$confirm(
          '请确认产品名称为"' + row.productName + '"是否已经上传完附件，完成后不能上传以及删除！',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            return completedCp(params);
          })
          .then(() => {
            this.getList();
            this.msgSuccess(`已完成`);
          })
          .catch(function () { });
      },

      //删除
      delFile(file) {
        console.log();
        delFile(file.id).then(res => {
          this.$message({ message: res.msg, type: 'success' });
        })
      },
      //文件详情
      getFile() {
        getFile({ tableId: this.rowId, tableName: 'quality_finished_examine' }).then(res => {
          this.upload.fileList = res.data.map(item => {
            if (item.fileName) {
              return { name: item.fileName, id: item.id, type: item.fileFormat, path: item.filePath }
            }
          })

        })
      },
      /** 上传按钮操作 */
      handleImport(row) {
        this.rowId = row.id
        this.upload.title = "上传成品检验单";
        this.upload.uploadShow = true
        this.upload.downloadShow = false
        this.upload.open = true;
      },
      //预览或者下载
      handlePreview(file) {
        console.log('file', file);
        if (file.type === 'png' || file.type === 'jpg') {
          this.upload.previewImage = config.devServer.proxy[process.env.VUE_APP_BASE_API].target + `system/file/getImgs?name=` + file.name
          console.log(' this.upload.previewImage ', this.upload.previewImage);
          this.upload.previewOpen = true
        } else {
          //下载
          this.downloadFile(file.name)
        }
      },
      downloadFile(value) {
        window.location.href = config.devServer.proxy[process.env.VUE_APP_BASE_API].target + 'system/file/download?resource=' + value;
      },
      // 文件超出个数的方法
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      // 附件详情按钮
      detail(row) {
        this.upload.title = "成品检验单附件详情";
        this.upload.uploadShow = false
        this.upload.downloadShow = true
        this.upload.open = true;
        this.rowId = row.id
        this.getFile()
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 提交上传文件
      async submitFileForm() {
        this.upload.submitLoading = true
        this.$refs.upload.submit();
        let fd = new FormData()// FormData 对象
        this.upload.uploadFiles.forEach(item => {
          return fd.append('file', item)
        })
        fd.append('tableName', 'quality_finished_examine')
        fd.append('tableId', this.rowId)
        let url = process.env.VUE_APP_BASE_API + "/system/file/uploads"
        let config = {
          headers:
            { Authorization: "Bearer " + getToken() }
        }
        Axios.post(url, fd, config).then(response => {
          console.log('response', response);
          if (response.status === 200) {
            this.upload.submitLoading = false
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$alert(response.data.msg, "导入结果", { dangerouslyUseHTMLString: true });
            this.getList();
          }
        })
      },
      // param是自带参数。 this.$refs.upload.submit() 会自动调用 httpRequest方法.在里面取得file
      httpRequest(param) {
        this.upload.uploadFiles.push(param.file)
      },

      /** 查询列表 */
      getList() {
        this.loading = true;
        getcpList(this.queryParams).then(
          (response) => {
            this.cpList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },

      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },

      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加成品检验单";
      },

      /** 提交按钮 */
      submitForm: function () {
        addCP(this.form).then((response) => {
          if (response.code === 200) {
            this.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }
        });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        this.$confirm(
          '是否确认删除产品名称为"' + row.productName + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delCp(row.id);
          })
          .then(() => {
            this.getList();
            this.msgSuccess("删除成功");
          })
          .catch(function () { });
      },

      /* 跳转 */
      goPage() {
        this.$router.push('/mass/testingGen/zlwt')
      }
    },
  };
</script>